/**
 * 
 */
package scan;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;

/**
 * @author mareshkau
 * 
 */
public class FileScanServlet extends HttpServlet {

	public static String USER_NAME = "net.username";
	public static String USER_PASS = "net.password";
	public static String WORKGROUP = "net.workgroup";
	/**
	 * 
	 */
	private static final long serialVersionUID = 3732575945172712502L;

	@Override
	protected synchronized void doGet(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		List<OneComputerThread> list = new ArrayList<OneComputerThread>();
		String userName = this.getServletContext().getInitParameter(FileScanServlet.USER_NAME);
		String userPassword = this.getServletContext().getInitParameter(FileScanServlet.USER_PASS);
		String workgroup = this.getServletContext().getInitParameter(FileScanServlet.WORKGROUP);
//scan samba
		PrintWriter out = resp.getWriter();
		try {
			// CheckAvailbleUtil.markNotAvailable();
			SmbFile smbFile = new SmbFile("smb://"+workgroup,
					new NtlmPasswordAuthentication(workgroup, userName, userPassword));
			for (SmbFile share : smbFile.listFiles()) {
				out.println(share.getCanonicalPath());
				OneComputerThread computerThread = new OneComputerThread(share,
						out);
				computerThread.start();
				list.add(computerThread);
			}
		} catch (Exception e) {
			e.printStackTrace(out);
		}
		//wait untill all thread will be finished
		for (OneComputerThread oneComputerThread : list) {
			try {
				oneComputerThread.join();
			} catch (InterruptedException e) {
				e.printStackTrace(out);
			}
		}
	
		out.println("FINISHED");
		out.flush();
		resp.flushBuffer();

	}
}
